package com.my.study.common.security.account;

import com.my.study.common.security.CustomAuthenticationFailureHandler;
import com.my.study.common.security.CustomAuthenticationSuccessHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.RememberMeServices;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 账号密码登录
 * 
 * @author yidujun
 * @date 2022/8/3 14:32
 */
//@Component("accountAuthenticationSecurityConfig")
public class AccountAuthenticationSecurityConfig 
        extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Resource(name = "customAuthenticationSuccessHandler")
    private CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;

    @Resource(name = "customAuthenticationFailureHandler")
    private CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Resource(name = "accountAuthenticationProvider")
    private AccountAuthenticationProvider accountAuthenticationProvider;
    
    @Resource(name = "rememberMeServices")
    private RememberMeServices rememberMeServices;
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
       super.configure(http);

        AccountAuthenticationProcessingFilter filter = new AccountAuthenticationProcessingFilter();
        filter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        filter.setAuthenticationSuccessHandler(customAuthenticationSuccessHandler);
        filter.setAuthenticationFailureHandler(customAuthenticationFailureHandler);
        
        filter.setRememberMeServices(rememberMeServices);
        
        http.authenticationProvider(accountAuthenticationProvider)
                .addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class);
    }
}
